package com.zjw.socket.demo.starter.messageService.service;

import com.google.gson.Gson;
import com.zjw.socket.demo.starter.annotation.core.Bean;
import com.zjw.socket.demo.starter.annotation.core.Inject;
import com.zjw.socket.demo.starter.messageService.*;
import com.zjw.socket.demo.starter.messageService.utils.GsonUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Bean
public class UserService {

  @Inject(query = "SimpleUserDataBase")
  public IUserDataBase userDataBase;

  public void addFriend(Message message, IConnectSession sender) {
    long fromId = message.getFromId();

    User user = userDataBase.queryUserByUsername(fromId);
    if (user == null) {
      return;
    }

    Message responseMessage = MessageCacheFactory.obtain();
    responseMessage.setType(SystemMessageType.RESPONSE_ADD_FRIEND_SUCCESS);
    responseMessage.setToId(user.username);
    sender.writeMessage(responseMessage);

    byte[] bytes = message.getBytes();
    long friendId = Long.parseLong(new String(bytes, StandardCharsets.UTF_8));
    User friend = userDataBase.queryUserByUsername(friendId);
    if (friend == null) {
      responseMessage.setType(SystemMessageType.RESPONSE_ADD_FRIEND_USER_NOT_EXIST);
      sender.writeMessage(responseMessage);
      return;
    }

    long meetTime = new Date().getTime();
    user.friends.add(friend.toFriend(meetTime));
    userDataBase.updateUser(user);

    friend.friends.add(user.toFriend(meetTime));
    userDataBase.updateUser(friend);

    responseMessage.setType(SystemMessageType.RESPONSE_ADD_FRIEND_SUCCESS);
    sender.writeMessage(responseMessage);
  }

  public void queryOtherUser(Message message, IConnectSession sender) {
    long toId = message.getToId();
    Message responseMessage = MessageCacheFactory.obtainResponseMessage(message);
    User user = userDataBase.queryUserByUsername(toId);
    if (user == null) {
      responseMessage.setType(SystemMessageType.RESPONSE_OTHERS_USER_INFO_NOT_EXIST);
      sender.writeMessage(responseMessage);
      return;
    }

    SimpleUser simpleUser = user.toSimpleUser();
    responseMessage.setType(SystemMessageType.RESPONSE_OTHERS_USER_INFO_SUCCESS);
    MessagePayloadUtils.setString(responseMessage, GsonUtils.GSON.toJson(simpleUser));
    sender.writeMessage(responseMessage);
  }
}
